package com.sun.local.top;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.sun.common.constants.Constant.SSQ_FILE_PATH;

/**
 * 各类数据排行榜（按年）
 * 备注：不需要联网，需要先获取到历史数据文件。
 */
public class TopYearData {

    public static void main(String[] args) throws Exception {
        getTopYearData();

    }

    private static void getTopYearData() throws IOException {
        // 读取文件数据
        List<String> lines = Files.readAllLines(Paths.get(SSQ_FILE_PATH));
        // 按年进行筛选
        Map<String, List<String>> yearMap = filterYear(lines);

        for (Map.Entry<String, List<String>> yearEntry : yearMap.entrySet()) {
            String year = yearEntry.getKey();
            List<String> yearList = yearEntry.getValue();
            // 获取Top数据
            System.out.println("#########################" + year + "年数据###########################");
            getTop(yearList,"AC", 3);
            getTop(yearList,"SerialNumber", 2);
            getTop(yearList,"SUM", 10);
            getTop(yearList,"OddEvenRatio", 3);
            getTop(yearList,"Distribution", 3);
        }
    }

    /**
     * 按年过滤数据
     */
    private static Map<String, List<String>> filterYear(List<String> lines) {
        Map<String, List<String>> yearMap = new LinkedHashMap<>();
        for (String ssq : lines) {
            // 年份-2023-08-40
            String year = ssq.substring(0, 4);
            // 双色球列表
            List<String> ssqList = yearMap.get(year);
            if(CollectionUtils.isNotEmpty(ssqList)) {
                ssqList.add(ssq);
            } else {
                ssqList = new ArrayList<>();
                ssqList.add(ssq);
            }
            yearMap.put(year, ssqList);
        }
        return yearMap;
    }

    /**
     * 获取Top数据并写出到文件ssq_top.text
     * @param lines 文件数据
     * @param type 类型
     * @param top 排名
     */
    private static void getTop(List<String> lines, String type, int top) {
        // 统计AC值出现次数
        Map<String, Long> acCounts = lines.stream()
                .filter(line -> line.contains(type + "="))
                .map(line -> StringUtils.substringBetween(line, type + "=", "|").trim())
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        // 获取排名前N的数据并写出
        acCounts.entrySet().stream()
                .sorted((e1, e2) -> e2.getValue().compareTo(e1.getValue()))
                .limit(top)
                .forEach(e -> {
                    // 写出数据
                    System.out.println(type + "=" + e.getKey() + ",Count=" + e.getValue());
                });
    }

}
